package es.ats.codington.web.servlets;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import es.ats.codington.festival.domain.Event;
import es.ats.codington.festival.services.EventDAOService;
import es.ats.codington.festival.services.EventSignUpService;
import es.ats.codington.festival.services.VisitorService;

/**
 * Servlet implementation class EventServlet
 */
@WebServlet("/EventServlet")
public class EventServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EventServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		EventSignUpService eventSignUpService = new EventSignUpService();
		EventDAOService eventDAOService = new EventDAOService();
		VisitorService visitorService = new VisitorService();
		ArrayList<Event> registeredEvents = new ArrayList<Event>();
		ArrayList<Event> unregisteredEvents = new ArrayList<Event>();
		ArrayList<Event> allEvents = new ArrayList<Event>();
		String userName = null;
		Cookie cookie= null;
		Cookie[] cookies=request.getCookies();
		if(cookies!=null){
			for(int i=0; i<cookies.length; i++){
				cookie=cookies[i];
				if(cookie.getName().compareTo("user")==0)
				userName=cookie.getValue();
				
			}
		}else{
			response.sendRedirect("login.jsp");
		}
		allEvents = eventDAOService.getEventListService();
		registeredEvents = eventSignUpService.eventForUserService(visitorService.getVisitorIdService(userName));
		unregisteredEvents = eventSignUpService.noEventForUserService(visitorService.getVisitorIdService(userName));
		
		request.setAttribute("allEvents", allEvents);
		request.setAttribute("registeredList", registeredEvents);
		request.setAttribute("unregisteredList", unregisteredEvents);
		RequestDispatcher rd= request.getRequestDispatcher("/events.jsp");
		rd.include(request, response);
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}
}
